package com.lipaluma.field.validator.impl.Enum;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.lipaluma.annotations.validations.Validate;
import com.lipaluma.context.Context;
import com.lipaluma.exceptions.CsvParserException;
import com.lipaluma.field.validator.impl.generic.AbstractIsIncludedInValidator;
import com.lipaluma.util.ParserUtils;
import com.lipaluma.util.ReflectionUtils;
import com.lipaluma.xml.validator.XmlIncludedInValidator;
import com.lipaluma.xml.validator.XmlValidator;

/**
 * Validate a Enum field to check that the value of the field must be included in at least one of different given values.<br/>
 * 
 * <p>
 * For Initialisation :
 * <ul>
 * 	<li>
 * 	<u><b>By annotations :</b></u> Use {@link Validate}, with the attribute <code>includedIn</code> 
 * to specify the list of values accepted. The given values must match with the values of the enum.<br/>
 * </li>
 * 	<li>
 * 	<u><b>By Xml :</b></u>
 * <ul>
 * This validator may be added using xml mapping with the element <code>includedIn</code> like below : <br/>
 * <code>
 * &lt;ToMap field="..."   ...><br/>
 * <b>
 * &nbsp;&nbsp;&nbsp;&lt;includedIn><br/>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value>ENUM_VALUE_1&lt;/value><br/>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value>ENUM_VALUE_2&lt;/value><br/>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value>ENUM_VALUE_3&lt;/value><br/>
 * &nbsp;&nbsp;&nbsp;&lt;/includedIn><br/>
 * </b>
 * &lt;/ToMap>
 * </code>
 * </li>
 * </ul>
 * @author Mario
 *
 */
public class EnumIncludedInValidator extends AbstractIsIncludedInValidator<Enum<?>> {

	public EnumIncludedInValidator() {}
	public EnumIncludedInValidator(Enum<?>... values) {
		if(values == null)
			throw new CsvParserException("Error on setting "+this.getClass()+" : given values can't be null");
		init(Arrays.asList(values));		
	}
	public EnumIncludedInValidator(List<Enum<?>> values) {
		if(values == null)
			throw new CsvParserException("Error on setting "+this.getClass()+" : given values can't be null");
		init(values);
	}
	
	@Override
	public boolean init(Context context, Field field) {
		Validate annotation = field.getAnnotation(Validate.class);
		if(annotation == null || annotation.includedIn().length == 0)
			return false;
		
		List<Enum<?>> enums = new ArrayList<Enum<?>>();
		for (String string : annotation.includedIn()) {
			enums.add(ParserUtils.parseToEnum(ReflectionUtils.getParameterizedClass(field), string));
		}
		init(enums);
		return true;
	}
	
	@Override
	public boolean init(Context context, Field field, XmlValidator xmlValidator) {
		XmlIncludedInValidator validator = (XmlIncludedInValidator) xmlValidator;
		List<Enum<?>> enums = new ArrayList<Enum<?>>();
		for (String value : validator.getValues()) {
			enums.add(ParserUtils.parseToEnum(ReflectionUtils.getParameterizedClass(field), value));
		}
		init(enums);
		return true;
	}

	
}
